import QQMapWX from '@/util/qqmap-wx-jssdk.min.js'
import appConfig from '@/config/appConfig.js'
import $infoBox from '@/common/fun.js'

// 默认地址信息
// #ifdef MP-YHDD
const DEFAULT_ADDRESS_INFO = { longitude: 125.32, latitude: 43.82, address: '长春市', isReject: true }
// #endif
// #ifndef MP-YHDD
const DEFAULT_ADDRESS_INFO = { longitude: 113.62536678210733, latitude: 34.7466287061769, address: '郑州市', isReject: true }
// #endif
/**
 * 获取定位授权
 */
async function getAuthorize() {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.userLocation',
			success: () => {
				resolve()
			},
			fail: () => {
				reject()
			}
		})
	})
}
/**
 * 获取定位信息
 */
async function getLocationInfo() {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			geocode: true,
			success: async ({ longitude, latitude }) => {
				resolve(getLocationQqmapsdk(longitude, latitude))
			},
			fail: () => {
				resolve(DEFAULT_ADDRESS_INFO) // 定位失败 返回郑州市政府 经纬度
			}
		})
	})
}
/**
 * 根据经纬度 反解析地址
 */
async function getLocationQqmapsdk(longitude, latitude) {
	// 实例化API核心类
	const qqmapsdk = new QQMapWX({
		key: appConfig.qqMapKey
	});
	return new Promise((resolve, reject) => {
		qqmapsdk.reverseGeocoder({
			location: {
				latitude,
				longitude
			},
			success: function({ result }) {
				resolve({ longitude, latitude, address: result.formatted_addresses.recommend || result.formatted_addresses.rough || result.address || DEFAULT_ADDRESS_INFO.address })
			},
			fail: function(res) {
				resolve({...DEFAULT_ADDRESS_INFO, longitude, latitude})
			}
		})
	})
}
/**
 * 拒绝授权后，弹框提示是否手动打开位置授权
 */
async function openConfirm() {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '请求授权当前位置',
			content: '我们需要获取地理位置信息',
			success: (res) => {
				if (res.confirm) {
					uni.openSetting().then((res) => {
						if (res.authSetting["scope.userLocation"] === true) {
							resolve(); // 打开地图权限设置
						} else {
							reject();
						}
					});
				} else if (res.cancel) {
					reject();
				}
			}
		})
	})
}
/**
 * 彻底拒绝位置获取
 */
function rejectGetLocation(msg = '授权失败，无法获取当前位置') {
	$infoBox.toast(msg,{ duration: 2000 })
}

/**
 * 
 */
async function init (msg) {
	return new Promise((resolve,reject) => {
		getAuthorize().then(() => {
			// 同意后获取
			getLocationInfo().then(res => {
				resolve(res)
			})
		}).catch(() => {
			// 不同意给出弹框，再次确认
			$infoBox.hideLoading()
			openConfirm().then(() => {
				$infoBox.tipLoading('加载中')
				getLocationInfo().then(res => {
					$infoBox.hideLoading()
					resolve(res)
				})
			}).catch(() => {
				// 彻底拒绝后 给出提示 并使用默认地址
				rejectGetLocation(msg)
				resolve(DEFAULT_ADDRESS_INFO)
			});
		});
	})
}

export default init
